<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="存储配置" prop="configId">
        <el-select v-model="queryParams.configId" placeholder="选择存储配置" clearable style="width: 240px"
                   @change="getBucketList">
          <el-option v-for="item in storageOptions" :key="item.configId" :label="item.configName"
                     :value="item.configId"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="getBucketList">查询</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleCreate" v-hasPermi="['file:bucket:add']">创建桶
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
                   v-hasPermi="['file:bucket:remove']">删除桶
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getBucketList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bucketList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" type="index" width="80" align="center"/>
      <el-table-column label="存储桶名称" align="center" prop="bucketName" width="300" :show-overflow-tooltip="true">
        <template #default="scope">
          {{ scope.row.bucketName }}
          <el-tag v-if="scope.row.isDefault" type="success" size="small" class="ml-2">默认</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="访问权限" align="center" prop="permission">
        <template #default="scope">
          <el-tag v-if="scope.row.permission === 'private'" type="info">私有</el-tag>
          <el-tag v-else-if="scope.row.permission === 'public-read'" type="success">公共读</el-tag>
          <el-tag v-else-if="scope.row.permission === 'public-read-write'" type="warning">公共读写</el-tag>
          <el-tag v-else-if="scope.row.permission === 'loading...'" type="" effect="plain">加载中</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="存储类型" align="center" prop="storageType">
        <template #default="scope">
          <el-tag v-if="currentConfig?.storageType === 'local'" type="danger">本地存储</el-tag>
          <el-tag v-else-if="currentConfig?.storageType === 'minio'" type="primary">MinIO</el-tag>
          <el-tag v-else-if="currentConfig?.storageType === 'aliyun'" type="success">阿里云OSS</el-tag>
          <el-tag v-else-if="currentConfig?.storageType === 'tencent'" type="info">腾讯云COS</el-tag>
          <el-tag v-else-if="currentConfig?.storageType === 'aws'" type="warning">AWS S3</el-tag>
          <el-tag v-else>{{ currentConfig?.storageType }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="配置名称" align="center" prop="configName" :show-overflow-tooltip="true">
        <template #default="scope">
          {{ currentConfig?.configName }}
        </template>
      </el-table-column>
      <el-table-column label="访问地址" align="center" prop="endpoint" :show-overflow-tooltip="true">
        <template #default="scope">
          {{ currentConfig?.endpoint }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="420" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleDetail(scope.row)" v-hasPermi="['file:bucket:list']">
            详情
          </el-button>
          <el-button link type="primary" icon="Setting" @click="handlePermission(scope.row)"
                     v-hasPermi="['file:bucket:edit']" v-if="currentConfig?.storageType !== 'local'">权限
          </el-button>
          <el-button link type="warning" icon="Connection" @click="handleCorsConfig(scope.row)"
                     v-hasPermi="['file:storage:cors']" v-if="currentConfig?.storageType !== 'local' && currentConfig?.storageType !== 'minio' && currentConfig?.enableDirectUpload === 1">CORS
          </el-button>
          <el-button link type="primary" icon="Star" @click="handleSetDefault(scope.row)"
                     v-hasPermi="['file:storage:edit']">设为默认
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['file:bucket:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 创建存储桶对话框 -->
    <el-dialog title="创建存储桶" v-model="createOpen" width="500px" append-to-body>
      <el-form ref="createRef" :model="createForm" :rules="createRules" label-width="100px">
        <el-form-item label="存储配置" prop="configId">
          <el-select v-model="createForm.configId" placeholder="请选择存储配置" style="width: 100%">
            <el-option v-for="item in storageOptions" :key="item.configId" :label="item.configName"
                       :value="item.configId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="桶名称" prop="bucketName">
          <el-input v-model="createForm.bucketName" :placeholder="getBucketNamePlaceholder()"/>
          <div class="el-form-item__tip">{{ getBucketNameTip() }}</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitCreate">确 定</el-button>
          <el-button @click="createCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 桶详情对话框 -->
    <el-dialog title="存储桶详情" v-model="detailOpen" width="600px" append-to-body>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="桶名称">{{ detailForm.bucketName }}</el-descriptions-item>
        <el-descriptions-item label="存储类型">
          <el-tag v-if="currentConfig?.storageType === 'minio'" type="primary">MinIO</el-tag>
          <el-tag v-else-if="currentConfig?.storageType === 'aliyun'" type="success">阿里云OSS</el-tag>
          <el-tag v-else-if="currentConfig?.storageType === 'tencent'" type="info">腾讯云COS</el-tag>
          <el-tag v-else-if="currentConfig?.storageType === 'aws'" type="warning">AWS S3</el-tag>
          <el-tag v-else>{{ currentConfig?.storageType }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="配置名称">{{ currentConfig?.configName }}</el-descriptions-item>
        <el-descriptions-item label="访问地址">{{ currentConfig?.endpoint }}</el-descriptions-item>
        <el-descriptions-item label="区域">{{ currentConfig?.region }}</el-descriptions-item>
        <el-descriptions-item label="自定义域名">{{ currentConfig?.domain || '未配置' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 权限设置对话框 -->
    <el-dialog title="设置存储桶权限" v-model="permissionOpen" width="500px" append-to-body>
      <el-form ref="permissionRef" :model="permissionForm" :rules="permissionRules" label-width="100px">
        <el-form-item label="桶名称">
          <el-input v-model="permissionForm.bucketName" disabled/>
        </el-form-item>
        <el-form-item label="访问权限" prop="permission">
          <el-radio-group v-model="permissionForm.permission">
            <el-radio value="private">私有</el-radio>
            <el-radio value="public-read">公共读</el-radio>
            <el-radio value="public-read-write">公共读写</el-radio>
          </el-radio-group>
          <div class="permission-tips">
            <div class="tip-item">
              <strong>私有：</strong>只有桶拥有者可以访问
            </div>
            <div class="tip-item">
              <strong>公共读：</strong>任何人都可以读取桶中的文件<span v-if="currentConfig?.storageType === 'minio'">，支持跨域访问</span>
            </div>
            <div class="tip-item">
              <strong>公共读写：</strong>任何人都可以读取和写入桶中的文件<span v-if="currentConfig?.storageType === 'minio'">，支持跨域访问和前端直传</span>
            </div>
            <div class="tip-item" v-if="currentConfig?.storageType === 'minio'">
              <strong>MinIO提示：</strong>设置为公共权限即可解决跨域问题，无需单独配置CORS
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitPermission">确 定</el-button>
          <el-button @click="permissionCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- CORS配置对话框 -->
    <el-dialog :title="`CORS配置管理 - ${corsForm.bucketName}`" v-model="corsOpen" width="600px" append-to-body>
      <div class="cors-info">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="存储桶">{{ corsForm.bucketName }}</el-descriptions-item>
          <el-descriptions-item label="存储配置">{{ corsForm.configName }}</el-descriptions-item>
          <el-descriptions-item label="当前状态">
            <div class="cors-status">
              <el-tag :type="getCorsStatusType(corsForm.status)" class="status-tag">
                {{ getCorsStatusText(corsForm.status) }}
              </el-tag>
              <div v-if="corsForm.status.length > 20" class="status-detail">
                {{ corsForm.status }}
              </div>
            </div>
          </el-descriptions-item>
        </el-descriptions>

          <div class="cors-description">
            <h4>CORS配置说明</h4>
            <ul v-if="currentConfig?.storageType === 'minio'">
              <li>MinIO通过Bucket Policy管理跨域访问权限</li>
              <li>设置为"公共读"或"公共读写"权限即自动支持跨域</li>
              <li>私有桶不支持跨域访问，需要先设置为公共权限</li>
              <li>无需单独配置CORS规则，权限设置即可解决跨域问题</li>
            </ul>
            <ul v-else-if="currentConfig?.storageType === 'tencent'">
              <li><strong>腾讯云COS专用CORS配置：</strong></li>
              <li>✅ 允许的请求方法：GET, POST, PUT, DELETE, HEAD, OPTIONS</li>
              <li>✅ 允许的请求头：*（所有，包括签名头）</li>
              <li>✅ 允许的来源：*（所有域名）</li>
              <li>✅ 优化了预签名URL的Content-Type处理</li>
              <li>✅ 缓存时间：24小时（腾讯云推荐）</li>
              <li>🔥 专门解决403 Forbidden跨域问题</li>
            </ul>
            <ul v-else>
              <li>配置CORS后可解决前端直传跨域问题</li>
              <li>允许的请求方法：GET, POST, PUT, DELETE, HEAD, OPTIONS</li>
              <li>允许的请求头：*（所有）</li>
              <li>允许的来源：*（所有域名）</li>
              <li>缓存时间：1小时</li>
            </ul>

          <div class="cors-warning">
            <h4>⚠️ 注意事项</h4>
            <ul v-if="currentConfig?.storageType === 'minio'">
              <li>MinIO的跨域访问通过存储桶权限控制</li>
              <li>配置CORS实际上是将存储桶设置为公共读写权限</li>
              <li>删除CORS配置会将存储桶设置为私有权限</li>
              <li>建议先在权限设置中调整桶权限，再考虑是否需要CORS配置</li>
            </ul>
            <ul v-else-if="currentConfig?.storageType === 'tencent'">
              <li><strong>腾讯云COS特殊注意事项：</strong></li>
              <li>🚨 必须配置CORS才能支持前端直传，否则会出现403 Forbidden错误</li>
              <li>⚙️ 已优化预签名URL的Content-Type签名处理</li>
              <li>🔒 已配置所有必要的CORS头部，包括OPTIONS预检请求</li>
              <li>🌐 生产环境建议将允许来源改为具体域名</li>
              <li>📝 配置后需要等待1-2分钟生效</li>
            </ul>
            <ul v-else>
              <li>CORS配置是针对整个存储桶的，不是单个文件</li>
              <li>生产环境建议限制具体的前端域名</li>
              <li>配置后所有使用此存储桶的应用都能直传</li>
            </ul>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="configureCorsForBucket" :loading="corsLoading">
            {{ getConfigureButtonText() }}
          </el-button>
          <el-button type="danger" @click="deleteCorsForBucket" v-if="corsForm.status.includes('已配置')" :loading="corsLoading">
            {{ getDeleteButtonText() }}
          </el-button>
          <el-button @click="corsOpen = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BucketManagement">
import {createBucket, deleteBucket, listBuckets, setBucketPermission} from "@/api/filemanager/bucket"
import {getStorageConfig, updateStorageConfig} from "@/api/filemanager/storage"
import {configureCors, getCorsStatus, deleteCors} from "@/api/filemanager/cors"
import {getFileConfigs} from '@/store/modules/fileConfig'

const {proxy} = getCurrentInstance()

// 存储配置列表
const storageOptions = ref([])
const currentConfig = ref(null)

const bucketList = ref([])
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)

// 创建桶对话框
const createOpen = ref(false)
const createForm = reactive({
  configId: undefined,
  bucketName: undefined
})
const createRules = {
  configId: [{required: true, message: "请选择存储配置", trigger: "change"}],
  bucketName: [
    {required: true, message: "桶名称不能为空", trigger: "blur"},
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('桶名称不能为空'))
          return
        }
        
        const selectedConfig = storageOptions.value.find(item => item.configId === createForm.configId)
        
        if (selectedConfig?.storageType === 'local') {
          // 本地存储目录名称验证规则较宽松
          if (value.length < 1 || value.length > 100) {
            callback(new Error('目录名称长度应在1-100个字符之间'))
          } else {
            callback()
          }
        } else if (selectedConfig?.storageType === 'tencent') {
          // 腾讯云COS桶名验证（必须包含APPID格式）
          if (!/.*-\d{10}$/.test(value)) {
            callback(new Error('腾讯云COS桶名称格式错误。正确格式为：桶名-APPID（如：mybucket-1234567890）'))
          } else if (value.length < 12 || value.length > 63) {
            callback(new Error('桶名称长度应在12-63个字符之间'))
          } else {
            callback()
          }
        } else {
          // 其他存储类型的标准验证
          if (!/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/.test(value)) {
            callback(new Error('桶名称只能包含小写字母、数字和连字符，长度3-63个字符'))
          } else {
            callback()
          }
        }
      },
      trigger: "blur"
    }
  ]
}

// 详情对话框
const detailOpen = ref(false)
const detailForm = reactive({
  bucketName: undefined
})

// 权限设置对话框
const permissionOpen = ref(false)
const permissionForm = reactive({
  bucketName: undefined,
  permission: 'private'
})
const permissionRules = {
  permission: [{required: true, message: "请选择访问权限", trigger: "change"}]
}

// CORS配置对话框
const corsOpen = ref(false)
const corsLoading = ref(false)
const corsForm = reactive({
  bucketName: undefined,
  configName: undefined,
  status: '未知状态'
})

const queryParams = reactive({
  configId: undefined
})

/** 查询存储配置列表（智能缓存，自动获取数据） */
async function loadStorageOptions() {
  try {
    // 直接获取所有存储配置，如果缓存为空会自动调用API
    storageOptions.value = await getFileConfigs({enabledOnly: false})

    // 默认选择第一个配置
    if (storageOptions.value.length > 0) {
      const defaultConfig = storageOptions.value.find(item => item.isDefault === 1) || storageOptions.value[0]
      queryParams.configId = defaultConfig.configId
      currentConfig.value = defaultConfig
      createForm.configId = defaultConfig.configId
      getBucketList()
    }
  } catch (error) {
    console.error('加载存储配置失败:', error)
  }
}

/** 查询存储桶列表 */
function getBucketList() {
  if (!queryParams.configId) {
    bucketList.value = []
    loading.value = false
    return
  }

  loading.value = true
  currentConfig.value = storageOptions.value.find(item => item.configId === queryParams.configId)

  listBuckets({configId: queryParams.configId}).then(response => {
    if (response.code === 200) {
      // 后端已经返回完整的桶信息（包含桶名称、权限、是否默认）
      bucketList.value = response.data || []
    } else {
      proxy.$modal.msgError(response.msg || "获取存储桶列表失败")
      bucketList.value = []
    }
    loading.value = false
  }).catch(error => {
    proxy.$modal.msgError("获取存储桶列表失败")
    bucketList.value = []
    loading.value = false
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  getBucketList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  if (storageOptions.value.length > 0) {
    const defaultConfig = storageOptions.value.find(item => item.isDefault === 1) || storageOptions.value[0]
    queryParams.configId = defaultConfig.configId
    currentConfig.value = defaultConfig
  }
  getBucketList()
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.bucketName)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleCreate() {
  createForm.configId = queryParams.configId
  createForm.bucketName = undefined
  createOpen.value = true
}

/** 详情按钮操作 */
function handleDetail(row) {
  detailForm.bucketName = row.bucketName
  detailOpen.value = true
}

/** 权限按钮操作 */
function handlePermission(row) {
  permissionForm.bucketName = row.bucketName
  permissionForm.permission = row.permission || 'private'
  permissionOpen.value = true
}

/** 提交创建 */
function submitCreate() {
  proxy.$refs["createRef"].validate(valid => {
    if (valid) {
      createBucket(createForm).then(response => {
        proxy.$modal.msgSuccess("创建成功")
        createOpen.value = false
        getBucketList()
      })
    }
  })
}

/** 取消创建 */
function createCancel() {
  createOpen.value = false
}

/** 提交权限设置 */
function submitPermission() {
  proxy.$refs["permissionRef"].validate(valid => {
    if (valid) {
      setBucketPermission({
        bucketName: permissionForm.bucketName,
        permission: permissionForm.permission,
        configId: queryParams.configId
      }).then(response => {
        proxy.$modal.msgSuccess("权限设置成功")
        permissionOpen.value = false
        getBucketList()
      })
    }
  })
}

/** 取消权限设置 */
function permissionCancel() {
  permissionOpen.value = false
}

/** 设置默认桶操作 */
function handleSetDefault(row) {
  if (row.isDefault) {
    proxy.$modal.msgWarning("该桶已经是默认桶")
    return
  }

  proxy.$modal.confirm(`是否确认将存储桶"${row.bucketName}"设置为当前存储配置的默认桶？`).then(function () {
    // 先获取完整的存储配置信息
    return getStorageConfig(queryParams.configId)
  }).then(response => {
    const configData = response.data
    configData.bucketName = row.bucketName

    // 更新存储配置
    return updateStorageConfig(configData)
  }).then(() => {
    proxy.$modal.msgSuccess("设置默认桶成功")
    // 更新当前配置信息
    currentConfig.value.bucketName = row.bucketName
    // 更新存储选项中的配置
    const configIndex = storageOptions.value.findIndex(item => item.configId === queryParams.configId)
    if (configIndex !== -1) {
      storageOptions.value[configIndex].bucketName = row.bucketName
    }
    // 重新获取桶列表以更新默认标识
    getBucketList()
  }).catch(() => {
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const bucketNames = row?.bucketName ? [row.bucketName] : ids.value
  const confirmMessage = `是否确认删除存储桶"${bucketNames.join('", "')}"？
  
⚠️ 注意：删除存储桶将会：
1. 先清空桶中的所有文件和文件夹
2. 然后删除存储桶本身
3. 此操作不可恢复，请谨慎操作`
  
  proxy.$modal.confirm(confirmMessage, '删除确认', {
    confirmButtonText: '确认删除',
    cancelButtonText: '取消',
    type: 'warning',
    dangerouslyUseHTMLString: true
  }).then(function () {
    const promises = bucketNames.map(bucketName =>
        deleteBucket({bucketName: bucketName, configId: queryParams.configId})
    )
    return Promise.all(promises)
  }).then(() => {
    getBucketList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {
  })
}

/** 获取桶名称占位符 */
function getBucketNamePlaceholder() {
  const selectedConfig = storageOptions.value.find(item => item.configId === createForm.configId)
  if (selectedConfig?.storageType === 'local') {
    return '请输入目录名称（如：images、documents）'
  } else if (selectedConfig?.storageType === 'tencent') {
    return '请输入完整桶名称（如：mybucket-1234567890，包含APPID）'
  }
  return '请输入存储桶名称（小写字母、数字、连字符）'
}

/** 获取桶名称提示信息 */
function getBucketNameTip() {
  const selectedConfig = storageOptions.value.find(item => item.configId === createForm.configId)
  if (selectedConfig?.storageType === 'local') {
    return '目录名称用于组织文件，支持中文、英文、数字和常见符号'
  } else if (selectedConfig?.storageType === 'tencent') {
    return '腾讯云COS桶名称格式为：桶名-APPID（如：mybucket-1234567890）。请输入完整的桶名称，包含您的10位数字APPID'
  }
  return '桶名称必须全局唯一，只能包含小写字母、数字和连字符，长度3-63个字符'
}

/** CORS配置管理 */
function handleCorsConfig(row) {
  const bucketName = row.bucketName
  const configName = currentConfig.value?.configName || '未知配置'
  
  // 设置对话框数据
  corsForm.bucketName = bucketName
  corsForm.configName = configName
  corsForm.status = '正在获取...'
  
  // 显示对话框
  corsOpen.value = true
  
  // 获取CORS状态
  getCorsStatus(queryParams.configId).then(response => {
    corsForm.status = response.status || "未知状态"
  }).catch(error => {
    corsForm.status = "获取失败"
    proxy.$modal.msgError("获取CORS状态失败：" + (error.msg || error.message || "未知错误"))
  })
}

/** 配置存储桶CORS */
function configureCorsForBucket() {
  corsLoading.value = true
  configureCors(queryParams.configId).then(response => {
    corsLoading.value = false
    corsForm.status = "CORS已配置"
    proxy.$modal.msgSuccess(response.msg || "CORS配置成功，现在可以进行前端直传了")
  }).catch(error => {
    corsLoading.value = false
    proxy.$modal.msgError("CORS配置失败：" + (error.msg || error.message || "未知错误"))
  })
}

/** 删除存储桶CORS配置 */
function deleteCorsForBucket() {
  proxy.$modal.confirm('是否确认删除当前的CORS配置？删除后前端将无法直传文件。', '删除确认', {
    confirmButtonText: '确认删除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    corsLoading.value = true
    deleteCors(queryParams.configId).then(response => {
      corsLoading.value = false
      corsForm.status = "未配置CORS"
      proxy.$modal.msgSuccess(response.msg || "CORS配置删除成功")
    }).catch(error => {
      corsLoading.value = false
      proxy.$modal.msgError("删除CORS配置失败：" + (error.msg || error.message || "未知错误"))
    })
  })
}

/** 获取CORS状态类型 */
function getCorsStatusType(status) {
  if (status.includes('已配置') || status.includes('CORS已配置')) {
    return 'success'
  } else if (status.includes('未配置') || status.includes('未找到') || status.includes('不存在')) {
    return 'info'
  } else if (status.includes('获取失败') || status.includes('失败') || status.includes('错误')) {
    return 'danger'
  } else if (status.includes('正在获取')) {
    return 'warning'
  } else {
    return 'warning'
  }
}

/** 获取CORS状态文本 */
function getCorsStatusText(status) {
  if (status.includes('已配置') || status.includes('CORS已配置')) {
    return '已配置'
  } else if (status.includes('未配置') || status.includes('未找到') || status.includes('不存在')) {
    return '未配置'
  } else if (status.includes('获取失败') || status.includes('失败')) {
    return '获取失败'
  } else if (status.includes('正在获取')) {
    return '正在获取...'
  } else if (status.length > 20) {
    return '详见下方'
  } else {
    return status
  }
}

/** 获取配置按钮文字 */
function getConfigureButtonText() {
  if (currentConfig.value?.storageType === 'minio') {
    return corsForm.status.includes('已配置') ? '重新设置为公共读写' : '设置为公共读写'
  } else {
    return corsForm.status.includes('已配置') ? '重新配置' : '配置CORS'
  }
}

/** 获取删除按钮文字 */
function getDeleteButtonText() {
  if (currentConfig.value?.storageType === 'minio') {
    return '设置为私有'
  } else {
    return '删除CORS配置'
  }
}

// 初始化
loadStorageOptions()
</script>

<style scoped>
.el-form-item__tip {
  color: #909399;
  font-size: 12px;
  line-height: 1.4;
  margin-top: 4px;
}

.permission-tips {
  margin-top: 12px;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e9ecef;
}

.tip-item {
  margin-bottom: 8px;
  font-size: 13px;
  color: #666;
  line-height: 1.4;
}

.tip-item:last-child {
  margin-bottom: 0;
}

.tip-item strong {
  color: #333;
}

.ml-2 {
  margin-left: 8px;
}

/* CORS配置对话框样式 */
.cors-info {
  .cors-status {
    .status-tag {
      margin-bottom: 8px;
    }
    
    .status-detail {
      font-size: 12px;
      color: #909399;
      line-height: 1.4;
      word-break: break-all;
      white-space: pre-wrap;
      background-color: #f5f7fa;
      padding: 8px;
      border-radius: 4px;
      border: 1px solid #dcdfe6;
      max-height: 100px;
      overflow-y: auto;
    }
  }
  
  .cors-description {
    margin-top: 20px;
    
    h4 {
      color: #409eff;
      margin: 16px 0 8px 0;
      font-size: 14px;
    }
    
    ul {
      margin: 8px 0;
      padding-left: 20px;
      
      li {
        margin-bottom: 6px;
        line-height: 1.5;
        color: #606266;
      }
    }
    
    .cors-warning {
      margin-top: 16px;
      padding: 12px;
      background-color: #fef0f0;
      border-radius: 4px;
      border: 1px solid #fbc4c4;
      
      h4 {
        color: #f56c6c;
        margin-top: 0;
      }
      
      ul li {
        color: #f56c6c;
      }
    }
  }
}
</style>
